package com.wejoy.video.middle.station.admin.scheduler;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.wejoy.video.middle.station.data.domain.system.SysCarmera;
import com.wejoy.video.middle.station.data.domain.system.SysDept;
import com.wejoy.video.middle.station.data.service.evs.IEvsHttpService;
import com.wejoy.video.middle.station.data.service.system.ISysCarmeraService;
import com.wejoy.video.middle.station.data.service.system.ISysDeptService;
import com.wejoy.video.middle.station.data.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author miracle_j
 * @desc  同步点位的告警类型 和部门点位数量
 * Create by 2024/4/7 5:45 PM
 */
@Component
public class DeptPointsTask extends BaseTask{
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IEvsHttpService evsHttpService;
    @Autowired
    private ISysCarmeraService sysCarmeraService;

    @Scheduled(cron = "0 0 0/1 * * ? ")
//    @Scheduled(cron = "0/2 * * * * ? ")
    @Override
    protected void execute() {
        logger.info("同步点位的告警类型【start】...");
        SysDept evsApiDept = new SysDept();
        evsApiDept.setParentId(-1);
        evsApiDept.setIncludeLower(true);
        List<SysDept> departments = evsHttpService.getDepartments(evsApiDept, evsHttpService.getToken());
        List<SysDept> allDeptList = sysDeptService.getList(new SysDept());
        List<SysCarmera> carmeraList = sysCarmeraService.getList(new SysCarmera());
        List<SysCarmera> carmeraListOld = new ArrayList<>();
        for (SysDept item : departments) {//查询部门下的点位列表
            JSONObject result = evsHttpService.getPoints(evsHttpService.getToken(), 80, 1, item.getId().intValue(),null,null);
            JSONArray points = result.getJSONArray("data");
            if (CollectionUtils.isEmpty(points)) {
                continue;
            }
            //点位总数
            Integer camerNum=0;
            //ai点位总数
            Integer aiCamerNum=0;
            //是否有设备离线
            Boolean isOffline = false;
            Optional<SysDept> sysDept = allDeptList.stream()
                    .filter(de -> de.getId().equals(item.getId()))
                    .findFirst();
            for (int i = 0; i < points.size(); i++) {
                camerNum=camerNum+1;
                JSONObject pointInfo = points.
                        getJSONObject(i);
                Long pointId = pointInfo.getLong("pointId");
                //查询点位详情
                JSONObject info = evsHttpService.getPointInfo(evsHttpService.getToken(), pointId);
                //算法场景和能力list
                JSONArray abilities = info.getJSONArray("data");
                String abilitie = "";
                for (int j = 0; j < abilities.size(); j++) {
                    JSONObject abilitiesJSONObject = abilities.getJSONObject(j);
                    JSONObject jsonObject = abilitiesJSONObject.getJSONObject("algorithmAbility");
                    if(!ObjectUtils.isEmpty(jsonObject)){
                        abilitie = abilitie + jsonObject.getString("type") + ",";
                    }
                }
                //是否存在点位表不存在则新增 存在则更新
                Optional<SysCarmera> deptOptional = carmeraList.stream()
                        .filter(de -> de.getId().equals(pointId))
                        .findFirst();
                SysCarmera sysCarmera = new SysCarmera();
                sysCarmera.setId(pointId);
                sysCarmera.setIsAi(!StringUtils.isEmpty(abilitie));
                if(!StringUtils.isEmpty(abilitie)){
                    aiCamerNum=aiCamerNum+1;
                }
                sysCarmera.setAiTypes(abilitie);
                sysCarmera.setDepId(item.getId());
                sysCarmera.setDepType(item.getDeptType());
                sysCarmera.setOnline(pointInfo.getString("pointStatus").equals("ONLINE"));
                if(!sysCarmera.getOnline()){
                    isOffline=true;
                }
                if(sysDept.isPresent()){
                    sysCarmera.setDepType(sysDept.get().getDeptType());
                }
                if (deptOptional.isPresent()) {
                    SysCarmera carmera = deptOptional.get();
                    carmeraListOld.add(carmera);
                    sysCarmeraService.updateSelectiveById(sysCarmera);
                } else {
                    sysCarmeraService.insertSelective(sysCarmera);
                    carmeraListOld.add(sysCarmera);
                }
            }
            //更新部门ai摄像头个数
            if(sysDept.isPresent()){
                SysDept dept = sysDept.get();
                if(!dept.getAiCameraCount().equals(aiCamerNum)||!dept.getCameraCount().equals(camerNum)){
                    dept.setCameraCount(camerNum);
                    dept.setAiCameraCount(aiCamerNum);
                    dept.setIsCarmerOffline(isOffline);
                    sysDeptService.updateSelectiveById(dept);
                }
            }else {
                item.setCameraCount(camerNum);
                item.setAiCameraCount(aiCamerNum);
                item.setIsCarmerOffline(isOffline);
                sysDeptService.insertSelective(item);
            }
        }
        List<SysCarmera> uniqueElements = carmeraList.stream()
                .filter(carmera -> !carmeraListOld.contains(carmera))
                .collect(Collectors.toList());
        uniqueElements.forEach(item->{
            sysCarmeraService.delete(item.getId(),"同步");
        });
        logger.info("同步点位的告警类型【end】...");
    }
}
